from server.app.cloud_ide.schema.tenant.request.tenant_create_request import TenantCreateRequest
from server.app.cloud_ide.schema.tenant.request.tenant_update_request import TenantUpdateRequest
from server.app.cloud_ide.service.tenant_service import TenantService
from behave import *

from server.framework.core.logger import logger
from server.framework.utils.kubernetes.kubernetes_client import KubernetesClient

tenant_service = TenantService()


@given('租户列表没有如下租户')
def 租户列表没有如下租户(context):
    tenants = tenant_service.list_tenant()
    tenant_names = [x['name'] for x in context.table]
    target_tenant_ids = [x.id for x in tenants if x.name in tenant_names]
    rs = tenant_service.delete_tenant(target_tenant_ids)
    assert rs


@step("查看租户详情列表")
def 查看租户详情列表(context):
    try:
        tenants = tenant_service.list_tenant()
        logger.info(tenants)

        all_tenants = tenant_service.get_all_tenants()
        logger.info(all_tenants)
        assert True
    except Exception as e:
        assert False, e


@step("新增租户,信息如下")
def 新增租户_信息如下(context):
    try:
        for row in context.table:
            create_tenant_request = TenantCreateRequest(
                name=row['name'],
                max_cpu=row['max_cpu'],
                max_memory=row['max_memory'],
                max_disk=row['max_disk'],
                allow_nodes=row['allow_nodes']
            )
        result = tenant_service.create_tenant(create_tenant_request)
        assert result
    except Exception as e:
        assert False, e


@step('查看租户[{tenant_name}]的详情信息')
def 查看租户_的详情信息(context, tenant_name):
    tenants = tenant_service.list_tenant()
    target = next((x for x in tenants if x.name == tenant_name), None)
    entity = tenant_service.get_tenant_info(target.id)
    assert entity is not None


@step('编辑租户[{tenant_name}]的详情信息,将用户信息修改为')
def 编辑租户_的详情信息_将用户信息修改为(context, tenant_name):
    tenants = tenant_service.list_tenant()
    target = next((x for x in tenants if x.name == tenant_name), None)
    tenant_info = tenant_service.get_tenant_info(target.id)
    tenent_update_request = TenantUpdateRequest(
        id=tenant_info.id,
        name=context.table[0]['name'],
        max_cpu=context.table[0]['max_cpu'],
        max_memory=context.table[0]['max_memory'],
        max_disk=context.table[0]['max_disk'],
        allow_nodes=context.table[0]['allow_nodes'],
    )
    rs = tenant_service.update_tenant(tenent_update_request)
    assert rs


@step('删除以下租户')
def 删除以下租户(context):
    tenants = tenant_service.list_tenant()
    tenant_names = [x['name'] for x in context.table]
    tenants_ids = [str(x.id) for x in tenants if x.name in tenant_names]
    rs = tenant_service.delete_tenant(tenants_ids)
    assert rs